package cc.lj.internal.mobilepay.application.utils;

import cc.lj.internal.core.exception.ServiceException;
import cc.lj.internal.core.utils.XmlUtils;
import cc.lj.internal.mobilepay.LjConfig;
import cc.lj.internal.mobilepay.infrastructure.excepion.MobilepayExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求中信类
 * @author liangxifeng
 * @date 2022/11/20 16:13
 */
@Slf4j
@Component
public class ReuqestCitic {
    @Autowired
    protected LjConfig ljConfig;

    /**
     * 请求中信服务器方法
     * @param info 请求入参
     * @return 中信服务返回值
     * @throws IOException
     */
    public Map<String,String> request(Map info) {
        // 数据排序及拼接处理
        String plain = Sign.sortByASCII(info);
        // 对待发送数据进行加签
        Resource resource = new ClassPathResource(ljConfig.getPrivateKey());
        // 定义返回map
        Map<String,String> resMap = new HashMap();
        try {
            //对请求数据签名
            //String priKey = resource.getURL().getPath();
            //String publicCer = new ClassPathResource(ljConfig.getPublicCer()).getURL().getPath();
            String sign = Sign.sign(plain, ljConfig.getPwd(), ljConfig.getPrivateKey() , ljConfig.getPublicCer());
            info.put("sign",sign);
            log.info("我们生成的请求-sign: " + sign);

            String res = null;
            res = HttpPost.connect(ljConfig.getCiticURL(), info);
            log.info("中信请求结果:"+res);
            //将返回值转换为map
            resMap = XmlUtils.xml2Map(res);
            //取出返回值中的sign,并从返回值的map中移除
            String resSign = (String) resMap.get("sign");
            resMap.remove("sign");


            //对返回值map进行排序
            String resStr = Sign.sortByASCII(resMap);
            //String citicTestKey = new ClassPathResource(ljConfig.getCiticKey()).getURL().getPath();
            Boolean resVerify = Sign.verifySign(resStr, resSign, ljConfig.getCiticKey());
            if(resVerify == true ){
                log.info("中信返回值sign验证成功");
            }else {
                log.info("中信返回值sign验证失败");
            }
            resMap.put("sign",resSign);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(MobilepayExceptionEnum.REQUEST_CITIC_ERROR);
        }
        return resMap;
    }
}
